/*
 * by newiice
 *
 *	netdebug.c
 */
 
#include "netdebug.h"
//#include <semaphore.h>

//indicates, if you are connected to the network.
static bool connected=false;
static lwp_t debugThread = LWP_THREAD_NULL;
static char newMsg[255];
static sem_t SemWrite;
static sem_t SemRead;
static sem_t SemMutex;


void * nd_connect_th(void * v){
	char ip[16];
	LWP_SemInit(&SemWrite, 1,1);
	LWP_SemInit(&SemRead, 1,1);
	LWP_SemInit(&SemMutex, 1,1);
	
	while(!connected)
		connected=(if_config(ip, NULL, NULL, true)==0);
	
	strcpy(newMsg,ip);
	strcat(newMsg," is connected");
	while(1){
		struct sockaddr_in server;	
		char message[256];
		if (connected){
			strcpy(message,">");
			LWP_SemWait(SemRead);
			LWP_SemWait(SemMutex);
			strcat(message,newMsg);
			LWP_SemPost(SemMutex);
			LWP_SemPost(SemWrite);
			strcat(message,"\n");
			
			s32 sock = net_socket (AF_INET, SOCK_STREAM, IPPROTO_IP);
			if (sock != INVALID_SOCKET) {
				memset (&server, 0, sizeof (server));
				server.sin_family = AF_INET;
				server.sin_port = htons (2002);
				server.sin_addr.s_addr = inet_addr(SERVER_ADDR);
				if (net_connect(sock, (struct sockaddr *) &server, sizeof(server))>=0){
					net_write(sock, message, strlen(message)+2);
					net_close (sock);
				}	
			}
		}
	}
	LWP_SuspendThread(debugThread);
} 

void nd_connect(void){

LWP_CreateThread (&debugThread, nd_connect_th, NULL, NULL, 0, 70);
LWP_ResumeThread (debugThread);
}



bool nd_sendMsg(const char *msg){	
	LWP_SemWait(SemWrite);
	LWP_SemWait(SemMutex);
	sprintf(newMsg,msg);
	LWP_SemPost(SemMutex);
	LWP_SemPost(SemRead);
	return 0;
}


